Macromedia Flex Article

Learning Flex Basics (Part 2): Creating a Simple Calculator with Macromedia Flex


Table of Contents

  1. Introduction
  2. Building the Calculator
  3. Create the Application Object
  4. Add a Panel for the Calculator
  5. Add the Calculator Display
  6. Add a Grid to Lay Out the Buttons
  7. Add the Calculator Buttons
  8. Create the CalculatorController Class
  9. Add Properties to the Controller Class
  10. Add Controller Methods
  11. Instantiate the CalculatorController Class
  12. Complete Code Listing for calculator.mxml
  13. Complete Code Listing for CalculatorController.as
  14. Where to Go From Here

Add Properties to the Controller Class

Look at the code you wrote for calculator.mxml and see how none of it accesses the controller class properties directly; the properties are private, with one exception. When you instantiate the controller class in the MXML application later, you set a property that holds a reference to the entire calculator object, so that you can reference objects such as the display Label in the calculator without having to pass the reference when you call controller methods. So, you will set one public property to hold that reference, and several private properties to handle the calculator events.

The general syntax for setting properties is:

[public|private] var propertyName:dataType[=initialValue];

For example:

private var name:String;

The properties to use, in addition to the public reference to the calculator object, are:

  • Two registers to hold temporary values in the calculator pending operations
  • A currentRegister value to track the register that the user modifies
  • A currentOperation value to track the pending operation

These would be sufficient to make the calculator work, but you will add a few additional properties to hold numerical equivalents of the register values (these must be strings so that you can append additional numbers as the user clicks buttons) and a results value to hold the operation results. These extra properties will simplify some of the code and make the logic clearer.

  1. Set the following properties at the beginning of the CalculatorController class block:

    Type Name Data Type Initial Value
    public calcView Object  
    private reg1 String "" (empty string)
    private reg2 String ""
    private result Number  
    private currentRegister String "reg1"
    private operation String "none"
    private r1 Number  
    private r2 Number